/**
 * UserUtil.java
 *
 *
 * $LastChangedBy: allen $
 * $LastChangedDate: 2007-12-03 12:17:25 +0800 $
 * $Revision: 1323 $
 */
package com.myspace.view.common;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.myspace.domain.User;
import com.myspace.common.util.ParamUtils;

/**
 *
 * @author Allen.Chen
 *
 */
public class UserUtil {

	private static Logger log = Logger.getLogger(UserUtil.class);

	public static boolean isLogin(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (session.getAttribute(Constant.USER) == null)
			return false;
		else
			return true;
	}

	public static boolean isMyHome(HttpServletRequest request) {
		if (!isLogin(request))
			return false;
		long userIdInSession = ((User) request.getSession().getAttribute(
				Constant.USER)).getId().longValue();
		long userIdInParam = ParamUtils.getLongParameter(request, "userId", -1);
		return userIdInParam == userIdInSession;
	}

	public static User getUser(HttpServletRequest request) {
		if (!isLogin(request))
			return null;
		return (User) request.getSession().getAttribute(Constant.USER);
	}

	public static String getPhotoPath(HttpServletRequest request, User user) {
		if (user == null || user.getPhoto() == null) {
			return Constant.DEFAULT_PHOTO;
		}
		String realPath = request.getSession().getServletContext().getRealPath(
				"/");
		String path = realPath + user.getId() + Constant.USER_IMAGE_SUFFIX;
		try {
			File file = new File(path);
			if (file.exists()) {
				return Constant.USER_IMAGE_PATH + user.getId()
						+ Constant.USER_IMAGE_SUFFIX;
			}
			FileUtils.writeByteArrayToFile(file, user.getPhoto());
		} catch (Exception e) {
			log.error(e);
			return Constant.DEFAULT_PHOTO;
		}
		return Constant.USER_IMAGE_PATH + user.getId()
				+ Constant.USER_IMAGE_SUFFIX;
	}

	public static void removePhoto(HttpServletRequest request, User user) {
		String realPath = request.getSession().getServletContext().getRealPath(
				"/");
		String path = realPath + user.getId() + Constant.USER_IMAGE_SUFFIX;
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}
	}

}
